package main

import (
	"github.com/jinzhu/gorm"
	_ "github.com/go-sql-driver/mysql"
	"fmt"
)

var DB *gorm.DB

type Dept struct {
	ID int
	Name string
}
func (d Dept) Parents() {
	//SELECT f.*, a.*
	//	FROM FlatTable as f
	//JOIN ClosureTable as a ON (f.id = a.descendant_id)
	//WHERE a.ancestor_id = 1;
	depts := []Dept{}

	DB.Where("dept_closure_tables.ancestor_id = ?", d.ID).
		Joins("join dept_closure_tables on (dept_closure_tables.descendant_id = depts.id)").
		Find(&depts)

	fmt.Printf("parents depts: %+v", depts)
}

func (d Dept) Childrens() {
	//SELECT f.*, a.*
	//	FROM FlatTable as f
	//JOIN ClosureTable as a ON (f.id = a.descendant_id)
	//WHERE a.ancestor_id = 1;
	depts := []Dept{}

	DB.Where("dept_closure_tables.descendant_id = ?", d.ID).
		Joins("join dept_closure_tables on (dept_closure_tables.ancestor_id = depts.id)").
		Find(&depts)

	fmt.Printf("childrens depts: %+v", depts)
}

func (Dept) UpdateChildrenCount() {
	// 更新子部门的数量
}

func (newDept Dept) Create() {
	// 创建的时候 所有父部门添加一条路径便可
}

func (d Dept) Del() {
	// 似乎直接删除所有相关的连接就可以
}

type DeptClosureTable struct {
	AncestorID int
	DescendantID int
}


func main() {
	DB, err := gorm.Open("mysql", "vagrant:vagrant@(vagrant:3306)/test?charset=utf8&parseTime=True&loc=Local")

	if err != nil {
		fmt.Errorf("err: %+v", err)
		return
	}
	fmt.Printf("%+v", DB)
	DB.LogMode(true)

	//db.CreateTable(&Dept{})
	//db.CreateTable(&DeptClosureTable{})

	//Dept{ID: 1}.Parents()
	//Dept{ID: 1}.Childrens()

	DB.Close()
}
